<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Loader;
use app\api\model\Login as loginModel;
use think\Request;

class Login extends Api
{
    public function _initialize()
    {
        parent::_initialize();
        $this->loginModel = new loginModel();
        $number           = makeNumber();
        $this->beforeLog($number);
        if (config('site.miniapp')) {
            $this->miniapp_AppID     = config('site.miniapp_AppID');
            $this->miniapp_AppSercet = config('site.miniapp_AppSecret');
            $this->miniappLoginUrl   = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->miniapp_AppID}&secret={$this->miniapp_AppSercet}";
        }
        if (config('site.wx_mp')) {
            $this->mp_AppID     = config('site.mp_AppID');
            $this->mp_AppSecret = config('site.mp_AppSecret');
            $this->mpLoginUrl   = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->mp_AppID}&secret={$this->mp_AppSecret}";
        }
    }

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->modelUser = new \app\common\model\User();
    }

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 小程序/公众号/App 登录
     * @return void
     */
    public function login()
    {
        $number = makeNumber();
        $param  = $this->request->param();
        $result = $this->validate($param, 'Login.login');
        if (true !== $result) $this->error($result, '', 0, $number);

        if ($param['loginType'] == 1) {
            if (!$param['miniappLoginCode']) $this->error('小程序未获取登录权限', '', '', $number);
            if (!$param['miniappMobileCode']) $this->error('小程序未获取手机号授权', '', '', $number);
            $param['loginTypeDevice'] = 'miniapp';
            $param['appID']           = $this->miniapp_AppID;
            $param['appSercet']       = $this->miniapp_AppSercet;
            $param['loginUrl']        = $this->miniappLoginUrl . "&js_code={$param['miniappLoginCode']}&grant_type=authorization_code";
        }
        if ($param['loginType'] == 2) {
            if (!$param['mpLoginCode']) $this->error('公众号未获取登录权限', '', '', $number);
            $param['loginTypeDevice'] = 'mp';
            $param['appID']           = $this->mp_AppID;
            $param['appSercet']       = $this->mp_AppSecret;
            $param['loginUrl']        = $this->mpLoginUrl . "&code={$param['mpLoginCode']}&grant_type=authorization_code";
        }
        if ($param['loginType'] == 3) {
            $param['loginTypeDevice'] = 'app';
        }
        $result = $this->loginModel->loginInfo($param);
        if ($result['status'] == 0) $this->error($result['msg'], '', '', $number);
        //判断是否登录或注册
        if ($param['loginTypeDevice'] == 'miniapp') $whereDevice['miniAppOpenId'] = $result['data']['miniAppOpenId'];
        if ($param['loginTypeDevice'] == 'mp') $whereDevice['mpOpenId'] = $result['data']['mpOpenId'];
        if ($param['loginTypeDevice'] == 'app') $whereDevice['appOpenId'] = $result['data']['appOpenId'];
        $field = "id as userId,username as userName,money as userMoney,token,mobile as userMobile,avatar as userAvatar";
        if ($result['data']['unionid']) {
            $getUserInfo = $this->modelUser->where(['unionid' => $result['data']['unionid']])->field($field)->find();
        } else {
            $getUserInfo = $this->modelUser->where($whereDevice)->field($field)->find();
        }
        if($getUserInfo){
            $ret = $this->auth->direct($getUserInfo['userId']);
        }else{
            $sex = $result['data']['sex'] ? $result['data']['sex'] : 1;
            $avatar = $result['data']['avatar'] ? $result['data']['avatar'] : config('site.avatar');
            $username = $result['data']['userName'] ? $result['data']['userName'] : nickname(1);
            $extend = [
                'unionid'       => $result['data']['unionid'],
                'appOpenId'     => $result['data']['appOpenId'],
                'mpOpenId'      => $result['data']['mpOpenId'],
                'miniAppOpenId' => $result['data']['miniAppOpenId'],
                'sex'           => $sex,
                'avatar'        => $avatar,
            ];
            $ret    = $this->auth->register($username, 123456, '', $result['data']['mobile'] ?? '', $extend);
        }
        if ($ret) {
            $data                             = ['userinfo' => $this->auth->getUserinfo()];
            $getMobileStatus                  = $this->getBindMobile($this->auth->id);
            $data['userinfo']['mobileStatus'] = $getMobileStatus['status'];
            $this->success(__('Sign up successful'), $data,'',$number);
        } else {
            $this->error($this->auth->getError(),'','',$number);
        }
    }

    /**
     * 获取是否绑定手机号
     */
    public function getBindMobile($uid)
    {
        $mobile = $this->modelUser::where('id', $uid)->value('mobile');
        if (!$mobile) return ['status' => 0];
        return ['status' => 1];
    }


}